package com.cskaoyan.dbcp;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 创建日期: 2022/06/05 14:58
 *
 * @author ciggar
 */
public class DBCPUtils {


    static DataSource dataSource;

    // 初始化
    static {

        // 加载配置文件
        Properties properties = new Properties();
        try {
//            properties.load(new FileInputStream("dbcp.properties"));
            // RootClassLoader  ExtendClassLoader  AppClassLoader
            ClassLoader classLoader = DatasourceDemo.class.getClassLoader();
            InputStream stream = classLoader.getResourceAsStream("dbcp.properties");


            URL url = classLoader.getResource("dbcp.properties");
            System.out.println("url:" + url);
            String path = url.getPath();
            System.out.println("path:" + path);
            FileInputStream fileInputStream = new FileInputStream(path);



            properties.load(fileInputStream);

            // 创建数据库连接池
            dataSource = BasicDataSourceFactory.createDataSource(properties);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }



    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;

    }

//    @Test
//    public void test01(){
//
//
//    }



}
